<template>
    <div>
        <el-input v-model="searchInfo" style="width: 50%" placeholder="搜素" clearable @input="searchInfoChange()"/>
        <el-button type="primary" style="margin-left: 2%" :loading="saveLoading" @click="saveInfo()">确 认</el-button>
        <el-table
            :data="filterInfoList"
            style="width: 100%; margin-bottom: 20px; margin-top: 20px;"
            row-key="id"
            border
            :stripe="true"
            :show-overflow-tooltip="true"
            ref="tableRef"
            class="tableContainer"
            max-height="50vh"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" :reserve-selection="true"/>
            <el-table-column v-for="item in propJson.tableFieldList"
                             :prop="item.variableField"
                             :label="item.variableLabel"
                             :align="item.isAlignCenter">
                <template #default="scope" v-if="item.showType === 'custom'">
                    <slot :name="item.variableLabelEN" :scope="scope"></slot>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script name="TableSelectionSearchComponent" setup lang="ts">
import {commonParamChange, getCommonParamInfo, sleep} from "@/utils/commonParamUtil";
import {buildRequestParam, MSOARequest} from "@/utils/serviceRequestUtil";
import request from "@/utils/request";
import jsonpath from "jsonpath";
import {ElNotification, TableInstance} from "element-plus";
import {computed, defineProps, ref} from "vue";

let props = defineProps(['propJson', 'commonParam']);
let propJson = computed(() => {return props['propJson']})
let commonParam = computed(() => {return props['commonParam']})

let infoList = ref([]);
let filterInfoList = ref([]);
let searchInfo = ref("");
let saveLoading = ref(false);
let mountedFlag = ref(false);

let tableRef = ref<TableInstance>();

init();
function init() {
    getInfoList()
    if (propJson.value.editFlag) {
        return
    }
    doMounted()
}

function handleSelectionChange(val) {
    // 修改关联的变量值
    commonParamChange(commonParam.value, propJson.value.selectVarParamName, val)
}

function searchInfoChange() {
    filterInfoList.value = [];
    // 遍历所有数据，查询出符合条件的数据
    infoList.value.forEach(res => {
        // 遍历需要过滤的字段
        for (let i = 0; i < propJson.value.tableSelectField.length; i++) {
            let temp = propJson.value.tableSelectField[i]
            if (temp in res) {
                if (res[temp].includes(searchInfo.value)) {
                    filterInfoList.value.push(res)
                    break;
                }
            }
        }
    })
}

function execThen(awaitObj) {
    awaitObj.flag = false;
}

function execCatch(awaitObj) {
    awaitObj.flag = false;
    awaitObj.res = false;
}

function doSubmitMSSA(buildRes, awaitObj, submitAction) {

}

function doSubmitMSOA(buildRes, awaitObj, submitAction) {
    MSOARequest(buildRes, submitAction.apiMethod, submitAction.apiPath,
        submitAction.apiResponseList, commonParam.value,
        execThen, execCatch, awaitObj)
}

function doSubmitRTSA(buildRes, awaitObj, submitAction) {

}

function doSubmitApi(submitAction, awaitObj) {
    // 构建入参
    let paramList = submitAction.apiParamList
    let buildRes = buildRequestParam(commonParam.value, paramList)
    // 根据api类型调用方法
    if (submitAction.apiType === "MSSA") {
        doSubmitMSSA(buildRes, awaitObj, submitAction)
    } else if (submitAction.apiType === "MSOA") {
        doSubmitMSOA(buildRes, awaitObj, submitAction)
    } else if (submitAction.apiType === "RTSA") {
        doSubmitRTSA(buildRes, awaitObj, submitAction)
    } else {
        awaitObj.flag = false
    }
}

function doSubmitVariable(submitAction, awaitObj) {
    // 获取字段名称
    let paramName = submitAction.variableParamName;
    // 获取要设置的值
    let value = submitAction.variableValue;
    commonParamChange(commonParam.value, paramName, value)
    awaitObj.flag = false
}

async function saveInfo() {
    saveLoading.value = true
    // 定义一个标志位，后续同步执行
    let awaitObj = {flag: false, res: true}
    // 遍历所有的取消动作
    for (let i = 0; i < propJson.value.submitActionList.length; i++) {
        let submitAction = propJson.value.submitActionList[i];
        // 根据不同的类型进行不同的处理
        let type = submitAction.type;
        while (awaitObj.flag) {
            await sleep(1)
        }
        if (type === "api") {
            awaitObj.flag = true
            doSubmitApi(submitAction, awaitObj);
        } else if (type === "variable") {
            awaitObj.flag = true
            doSubmitVariable(submitAction, awaitObj)
        }
    }
    saveLoading.value = false
    if (awaitObj.res) {
        ElNotification({
            title: 'Success',
            message: "成功",
            type: 'success'
        });
    } else {
        ElNotification({
            title: 'Error',
            message: "失败",
            type: 'error'
        });
    }
}

function doCustom() {
    if (propJson.value.tableDataCustomType === "Array") {
        if (Array.isArray(propJson.value.tableDataCustomInfo)) {
            filterInfoList.value = propJson.value.tableDataCustomInfo
            infoList.value = propJson.value.tableDataCustomInfo
        } else {
            let newStr = propJson.value.tableDataCustomInfo.replaceAll("\'", "\"");
            let infoList = JSON.parse(newStr)
            filterInfoList.value = infoList
            infoList.value = infoList
        }
    }
    mountedFlag.value = true
}

function doVariable() {
    let res = getCommonParamInfo(commonParam.value, propJson.value.tableDataVariableParam)
    filterInfoList.value = res
    infoList.value = res
    mountedFlag.value = true
}

function doMSOA(buildRes) {
    let methodType = "";
    if (propJson.value.apiMethod === 'GET') {
        methodType = "get";
    } else if (propJson.value.apiMethod === 'POST') {
        methodType = "post";
    }
    request({
        url: propJson.value.apiPath,
        method: methodType,
        data: buildRes
    }).then(res => {
        let jsonRes = jsonpath.query(res, propJson.value.responseJsonPath)
        filterInfoList.value = jsonRes
        infoList.value = jsonRes
        mountedFlag.value = true
    })
}

function doMSSA(buildRes) {

}

function doRTSA(buildRes) {

}

function doApi() {
    if (propJson.value.editFlag) {
        return
    }
    // 构建参数
    let paramList = propJson.value.queryListRequestList
    let buildRes = buildRequestParam(commonParam.value, paramList)
    // 服务调用
    if (propJson.value.apiType === "MSSA") {
        doMSSA(buildRes)
    } else if (propJson.value.apiType === "MSOA") {
        doMSOA(buildRes)
    } else if (propJson.value.apiType === "RTSA") {
        doRTSA(buildRes)
    }
}

function getInfoList() {
    // 判断表格的数据类型
    if (propJson.value.tableDataType === "custom") {
        doCustom()
    } else if (propJson.value.tableDataType === "variable") {
        doVariable()
    } else if (propJson.value.tableDataType === "api") {
        doApi()
    }
}

function doSelectedCustom() {
    if (propJson.value.selectedDataCustomType === "Array") {
        if (Array.isArray(propJson.value.selectedDataCustomInfo)) {
            let data = propJson.value.selectedDataCustomInfo
            resetSelectList(data)
        } else {
            let newStr = propJson.value.selectedDataCustomInfo.replaceAll("\'", "\"");
            let infoList = JSON.parse(newStr)
            resetSelectList(infoList)
        }
    }
}

function doSelectedVariable() {
    let res = getCommonParamInfo(commonParam.value, propJson.value.selectedDataVariableParam)
    resetSelectList(res)
}

function doSelectedApi() {
    // 构建参数
    let paramList = propJson.value.selectedListRequestList
    let buildRes = buildRequestParam(commonParam.value, paramList)
    // 服务调用
    if (propJson.value.selectedApiType === "MSSA") {
        doSelectedMSSA(buildRes)
    } else if (propJson.value.selectedApiType === "MSOA") {
        doSelectedMSOA(buildRes)
    } else if (propJson.value.selectedApiType === "RTSA") {
        doSelectedRTSA(buildRes)
    }
}

function resetSelectList(data) {
    data.forEach(info => {
        for (let i = 0; i < infoList.value.length; i++) {
            // 根据要匹配的字段进行匹配
            let matchField = propJson.value.selectedMatchField
            if (infoList.value[i][matchField] === info[matchField]) {
                tableRef.value.toggleRowSelection(infoList.value[i], true);
            }
        }
    })
}

function doSelectedMSOA(buildRes) {
    let methodType = "";
    if (propJson.value.selectedApiMethod === 'GET') {
        methodType = "get";
    } else if (propJson.value.selectedApiMethod === 'POST') {
        methodType = "post";
    }
    request({
        url: propJson.value.selectedApiPath,
        method: methodType,
        data: buildRes
    }).then(res => {
        let jsonRes = jsonpath.query(res, propJson.value.selectedResponseJsonPath)
        resetSelectList(jsonRes)
    })
}

function doSelectedMSSA(buildRes) {

}

function doSelectedRTSA(buildRes) {

}

async function doMounted() {
    while (!mountedFlag.value) {
        await sleep(0.5)
    }
    tableRef.value.clearSelection();
    // 判断表格的数据类型
    if (propJson.value.selectedDataType === "custom") {
        doSelectedCustom()
    } else if (propJson.value.selectedDataType === "variable") {
        doSelectedVariable()
    } else if (propJson.value.selectedDataType === "api") {
        doSelectedApi()
    }
}
</script>

<style scoped lang="less">

</style>